﻿using System.Collections.Generic;
using System.IO;
using XLua;

public class LuaMgr : Singleton<LuaMgr>, IZUpdate
{
    private Dictionary<string, string> luaScripts;
    private LuaObjectMgr luaObjMgr;
    private LuaTable luaTable;
    private LuaEnv luaEnv;

    public LuaMgr()
    {
        luaScripts = new Dictionary<string, string>();
        luaEnv = new LuaEnv(); ClearData();
        UpdateMgr.GetSingleton().AddUpdate(this);
    }

    public void ClearData()
    {
        luaScripts.Clear();
        luaEnv.Dispose();
    }

    public void ZUpdate()
    {
        luaEnv.Tick();
    }

    public void RunLoadLua()
    {
        luaEnv.DoString(GetLuaCode("RequireGlobal.lua"));
        luaObjMgr = AllUpdate.ConsoleLike.AddComponent<LuaObjectMgr>();
    }

    public void InitData(LuaData data)
    {
        for (int idx = 0; idx < data.names.Count; ++idx)
        {
            string name = data.names[idx];
            string code = data.codes[idx];
            luaScripts.Add(name, code);
        }
    }

    public string GetLuaCode(string fileName)
    {
        string path = PathUtil.GetLuaPath(fileName);
        string code = File.ReadAllText(path);
        if (Utility.GetPlatForm() != EPlatform.Editor)
        {
            path = path.Replace(".", "_");
            code = luaScripts[path];
        }
        return code;
    }
    
    public void PushLuaEvent(string eventStr, object param = null)
    {
        if (luaObjMgr == null) { return; }
        luaObjMgr.PushLuaEvent(eventStr, param);
    }

    public LuaTable GetLuaTable(string fileName)
    {
        return luaEnv.Global.Get<LuaTable>(fileName);
    }
    
    public void LoadLuaMsg()
    {

    }

    public void RecvLuaMsg(LuaMsg luaMsg)
    {
        
    }
}